## This software is licensed by the MIT License, see LICENSE file ##
##                                    Copyright © 2022 whitemangl ##

import asyncio
from aiogram.types import Message
from aiogram.types import CallbackQuery

from utils import TGPBot
from utils import switch_media

class TGPBotCallbackCallException(Exception):
    def __init__(self, data):
        super().__init__(f"Unexpected command \"{data}\"")


async def __on_prod_channel_callback_call(cb: CallbackQuery, bot: TGPBot):
    await asyncio.sleep(0)

async def __on_tech_channel_callback_call(cb: CallbackQuery, bot: TGPBot):
    #await bot.answer_callback_query(cb.id)

    if (cb.message.entities and f"https://t.me/c/{bot.tech_channel}" in cb.message.entities[0].url):

        message_id = int(cb.message.entities[0].url.split('/')[-1])

        if cb.data == "confirm":
            group = list()

            for message in bot.message_groups[message_id]:
                media = switch_media(message)
                if message.caption:
                    media.caption = message.caption
                group.append(media)

            await bot.send_media_group(bot.prod_channel, group, )

        elif cb.data != "cancel": TGPBotCallbackCallException(cb.data)

        for message in bot.message_groups[message_id]:
            await message.delete()

        bot.message_groups.pop(message_id)

    elif cb.data == "confirm":
        await bot.copy_message(int(bot.prod_channel), int(bot.tech_channel), cb.message.message_id)
    elif cb.data != "cancel": TGPBotCallbackCallException(cb.data)

    await cb.message.delete()

async def __on_ignore(message: Message, bot: TGPBot):
    await asyncio.sleep(0)

async def on_callback_call(cb: CallbackQuery, bot: TGPBot):
    if   cb.message.chat.id == int(bot.prod_channel): await __on_prod_channel_callback_call(cb, bot)
    elif cb.message.chat.id == int(bot.tech_channel): await __on_tech_channel_callback_call(cb, bot)
    else: await __on_ignore(cb, bot)
